package com.upsuns.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

import com.upsuns.util.QueryHandler;

/**
 *@Description:<p></p><br/>
 *@author 王旭
 *@time 2016年3月17日 下午10:01:15
 */
public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer>{

	private AsynchronousSocketChannel socketChannel;
	
	public ReadCompletionHandler(AsynchronousSocketChannel socketChannel) {
		if(this.socketChannel == null)
			this.socketChannel = socketChannel;
	}
	
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		attachment.flip(); //准备读数据
		byte[] reqBytes = new byte[attachment.remaining()];
		
		attachment.get(reqBytes);
		
		try {
			String req = new String(reqBytes, "utf-8");
			String resp = QueryHandler.handleQuery(req);
			byte[] respBytes = resp.getBytes();
			
			ByteBuffer respBuffer = ByteBuffer.allocate(respBytes.length);
			respBuffer.put(respBytes);
			respBuffer.flip();
			this.socketChannel.write(respBuffer, respBuffer, new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					if(attachment.hasRemaining())
						socketChannel.write(respBuffer, respBuffer, this);
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					try {
						socketChannel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			socketChannel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	

}
